<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">

      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-form label-width="70px" size="small">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
              <el-form-item label="业务日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startBusDate"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endBusDate"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="6">
              <el-form-item label="单据编码">
                <el-input v-model="query.code"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="6">
              <el-form-item label="部门">
                <zSelect :value.sync="query.deptIds" url="api/dropDown/childSysDeptList" style="width:  100%"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="6">
              <el-form-item label="人员">
                <zSelect :value.sync="query.userIds" url="api/dropDown/sysUserList" style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <rrOperation :crud="crud"/>
          </el-row>
        </el-form>
      </div>
      <crudOperation>
        <!-- <el-button type="primary" @click="toAdd" slot="left">新增</el-button> -->
        <el-button type="primary" @click="todel(crud.selections)" slot="left" :disabled="crud.selections.some(item=>item.status!==1)">删除</el-button>
        <el-button type="primary" @click="supervisor(crud.selections)" slot="left" :disabled="crud.selections.some(item=>item.status!==1)">主管审核</el-button>
        <el-button type="primary" @click="hr(crud.selections)" slot="left" :disabled="crud.selections.some(item=>item.status!==1)">人事审核</el-button>
        <el-button type="primary" @click="manager(crud.selections)" slot="left" :disabled="crud.selections.some(item=>item.status===4)">经理审核</el-button>
        <el-button type="primary" @click="reject(crud.selections)" slot="left" :disabled="crud.selections.some(item=>item.status===1)">反审</el-button>
      </crudOperation>
    </div>
    <!-- 表单渲染 -->
    <el-dialog :before-close="cancelCU" :close-on-click-modal="false" :title="title"
               :visible.sync="flag" append-to-body width="520px">
      <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="80px" size="small">
        <el-form-item label="打卡类型" label-width="85px" prop="type">
          <el-select v-model="form.type" placeholder="请选择" style="width: 160px">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="补卡时间" prop="replaceTime">
          <el-date-picker
            v-model="form.replaceTime"
            type="datetime"
            size="small"
            class="date-item"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="{
              disabledDate(time) {
                return time.getTime() > Date.now()
              },
              selectableRange: startTimeRange
            }"
          />
        </el-form-item>
        <el-form-item label="补卡原因" prop="reason">
          <el-input v-model="form.reason" style="width: 145px;"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" rows="5" style="width: 380px;" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancelCU">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="submitCU">确认</el-button>
      </div>
    </el-dialog>
    <div class="body-container">
      <!--表格渲染-->
      <el-table ref="table"  border
                height="700"
                show-summary
                v-loading="crud.loading"
                :data="crud.data"
                size="small"
                style="width: 100%;"
                :summary-method="crud.sumRow"
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                @selection-change="crud.selectionChangeHandler">
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60" />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('busDate')" prop="busDate" label="日期"  width="150px"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('imgUrl')" prop="imgUrl" label="图片"  width="150px">
          <template slot-scope="scope" >
            <el-image v-if="scope.row.imgUrl"
              style="width: 50px; height: 50px"
              :src="scope.row.imgUrl" 
              :fit="fit" />
              <span v-else>无</span>
          </template>
        </el-table-column>

        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('code')" prop="code" label="编码"  width="150px"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('userId')" prop="userName" label="人员" width="120px" />
                <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('deptId')" prop="deptName" label="部门" width="120px" />
                <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('type')" prop="type" label="打卡类型">
                  <template slot-scope="scope">
                    {{ dict.label.dict_Clock_type[scope.row.type] }}
                  </template>
                </el-table-column>
                <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('replaceTime')" prop="replaceTime" label="补卡时间"  width="180px"/>
                <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('reason')" prop="reason" label="补卡原因" />
                <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('status')" prop="status" label="状态"  width="150px">
                  <template slot-scope="scope">
                    {{ dict.label.dict_process_status[scope.row.status] }}
                  </template>
                </el-table-column>
                <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注"   width="120px"/>
        <el-table-column fixed="right" :render-header="crud.renderHeader" label="操作" width="150px" align="center">
          <template slot-scope="scope">
              <i slot="reference" class="el-icon-delete opration_icon_btn" type="primary" @click="toDelete((scope.row.id))" />
              <i class="el-icon-edit opration_icon_btn" style="margin-right: 14px" @click="toEdit(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
  </div>
</template>

<script>
  import crudBuClasses,{add,queryOne,del,supervisorPass,hrPass,managerPass ,reject} from '@/api/erp/buClasses'
  import CRUD, {crud, form, header, presenter} from '@crud/crud'
  import rrOperation from '@crud/RR.operation'
  import crudOperation from '@crud/CRUD.operation'
  import udOperation from '@crud/UD.operation'
  import pagination from '@crud/Pagination'
  import TreeSelect from '@riophae/vue-treeselect'
  // crud交由presenter持有
  const defaultCrud = CRUD({
    title: '补卡单', url: '/api/laterSign/queryAll', sort: 'id,desc', crudMethod: {...crudBuClasses}, optShow: {
      add: false,
    },
    props:{
    }
  });
  const defaultForm = {
    replaceTime: '',
    type: '',
    reason:'',
    remark:''
  };
  export default {
    name: 'buClasses',
    components: {pagination, crudOperation, rrOperation, udOperation,TreeSelect},
    dicts:['dict_process_status','dict_Clock_type'],
    mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
    directives:{
      tapDate:{
        inserted(el, binding, vnode, oldVnode){
          console.log(vnode.child.$vnode.child)
          vnode.child.$vnode.$options.value = '20022'
          console.log(vnode.child.$vnode.child.popperElm)
         }
      }
    },
    data() {
      return {
        flag:false,
        title:'',
        multiple:true,
        rules: {},
        // curDate:'',
        brandList: [],
        typeList: [
        {label: '上班打卡', value: 1},
        {label: '下班打卡', value: 2},
        ],
        startTimeRange:null,
      }
    },
    watch: {
    'form.replaceTime': {
      deep:true,
      handler(newValue, oldValue) {
        if (newValue) {
          let dateTime = ''//如果安装了moment.js,可以使用moment直接获取当前年月日时分秒
          const yy = new Date().getFullYear()
          const mm = new Date().getMonth() + 1
          const dd = new Date().getDate() < 10 ? "0" + new Date().getDate(): new Date().getDate();
          const hh = new Date().getHours()
          const mz = mm < 10 ? '0' + mm : mm
          const mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
          const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
          dateTime = yy + '-' + mz + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
          const dt = dateTime.split(' ')
          let st = ''

          if (newValue.split(' ')[0] === dt[0]) {
            // 如果点击的是今天的日期,可选择的时间开始为 00：00:00 至 此刻的时分秒
            st = dt[1];
            this.startTimeRange = ['00:00:00 - ' + st];
          } else {
            // 点击今天之前的日期的话，时间选择为：00:00:00- 23:59:59
            st = '23:59:59'
            this.startTimeRange = ['00:00:00 - ' + st]
          }
          // 例如：如果今天此刻时间为10:41:40 则选择时间范围为：00:00:00 - 10:41:40
          // 否则为：00:00:00- 23:59:59
        }
      }
    }
  },
    updated() {
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })},
    created() {
      // const date = new Date()
      // const month = date.getMonth() + 1
      // const day = date.getDate()
      // this.curDate = `${date.getFullYear()}-${month<10?'0'+month:month}-${day<10?'0'+day:day}`
      // this.getTypeList()
    },
    methods: {
      toAdd(){
        this.flag=true
        this.title='新增补卡单'
        this.form={}
      },
      toEdit(row){
        if (row.status!==1) {
          this.$notify.error({
          title: '错误',
          message: '当前在审核状态不能修改'
        });
        }else{
          this.flag=true
          this.form={
              id:row.id,
              replaceTime:row.replaceTime,
              type:row.type,
              reason:row.reason,
              remark:row.remark
          }
          this.title='编辑补卡单'
        }
        
      },
      toDelete(id){
        del([id]).then(res=>{
          this.crud.refresh()
          this.$message({
              message: res.msg,
              type: 'success'
            });
        })
      },
      todel(val){
        const data=val.map(item=>{
        return item.id
        })
        del(data).then(res=>{
          this.crud.refresh()
          this.$message({
              message: res.msg,
              type: 'success'
            });
        })
      },
      submitCU(){
        this.flag=!this.flag
        add(this.form).then(res=>{
          this.crud.refresh()
        })
      },
      cancelCU(){
        this.flag=!this.flag
      },
      supervisor(val){
        const data=val.map(item=>{
        return item.id
        })
        supervisorPass(data).then(res=>{
          this.crud.refresh()
          this.$message({
              message: res.msg,
              type: 'success'
            });
        })
      },
      hr(val){
        const data=val.map(item=>{
        return item.id
        })
        hrPass(data).then(res=>{
          this.crud.refresh()
          this.$message({
              message: res.msg,
              type: 'success'
            });
        })
      },
      manager(val){
        const data=val.map(item=>{
        return item.id
        })
        managerPass(data).then(res=>{
          this.crud.refresh()
          this.$message({
              message: res.msg,
              type: 'success'
            });
        })
      },
      reject(val){
        const data=val.map(item=>{
        return item.id
        })
        reject(data).then(res=>{
          this.crud.refresh()
          this.$message({
              message: res.msg,
              type: 'success'
            });
        })
      },
      // 获取数据前设置好接口地址
      [CRUD.HOOK.beforeRefresh]() {
        return true
      }, // 新增与编辑前做的操作
      [CRUD.HOOK.afterToCU](crud, form) {
      },
      //添加提交
      [CRUD.HOOK.afterValidateCU](crud) {
        // if (crud.form.dataScope === '自定义' && crud.form.depts.length === 0) {
        //   this.$message({
        //     message: '自定义数据权限不能为空',
        //     type: 'warning'
        //   })
        //   return false
        // } else if (crud.form.dataScope === '自定义') {
        //   const depts = []
        //   crud.form.depts.forEach(function (data, index) {
        //     const dept = {id: data}
        //     depts.push(dept)
        //   })
        //   crud.form.depts = depts
        // } else {
        //   crud.form.depts = []
        // }
        // return true
      }
    }
  }
</script>

<style scoped>
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
</style>
